%% Author: vjache
%% Created: 15.04.2009
%% Description: TODO: Add description to data_gen_utility
-module(data_gen_utility).

%%
%% Include files
%%
-include("../include/test.hrl").

%%
%% Exported Functions
%%
-export([
		 read_lines/1,
		 gen_triples/2,
		 cat/1]).

%%
%% API Functions
%%

read_lines(Filename) ->
	{ok,Dev}=file:open(Filename, [read]),
	loop(Dev,[]).
loop(Dev,Lines) ->
	case io:get_line(Dev,in) of
		eof ->
			Lines;
		Line ->
			loop(Dev,[string:strip(string:strip(Line, right, $\n),right,$\t)|Lines])
	end.

gen_triples(Num,Config) ->
	gen_triples(?CONFIG(data_dir,Config)++"/names.txt",
				?CONFIG(data_dir,Config)++"/familynames.txt",
				?CONFIG(data_dir,Config)++"/interests.txt",
				Num,Config).
gen_triples(NameFile,FNameFile,InterestsFile,Num,Config) ->
	Names=read_lines(NameFile),
	FNames=read_lines(FNameFile),
	Interests=read_lines(InterestsFile),
	TNames=lists:foldl(fun(Name,T)->
						gb_trees:insert(gb_trees:size(T), Name, T)
				end, gb_trees:empty(), Names),
	TFNames=lists:foldl(fun(FName,T)->
						gb_trees:insert(gb_trees:size(T), FName, T)
				end, gb_trees:empty(), FNames),
	TInterests=lists:foldl(fun(Interest,T)->
						gb_trees:insert(gb_trees:size(T), Interest, T)
				end, gb_trees:empty(), Interests),
	{ok,Dev}=file:open(?CONFIG(data_dir,Config)++"/triple.txt", [write]),
	gt_loop(TNames,TFNames,TInterests,Num,Dev).

gt_loop(_TNames,_TFNames,_TInterests,0,Dev) ->
	file:close(Dev);
gt_loop(TNames,TFNames,TInterests,Num,Dev) ->
	NameId=random:uniform(gb_trees:size(TNames))-1,
	Name=gb_trees:get(NameId, TNames),
	FNameId=random:uniform(gb_trees:size(TFNames))-1,
	FName=gb_trees:get(FNameId, TFNames),
	InterestId=random:uniform(gb_trees:size(TInterests))-1,
	Interest=gb_trees:get(InterestId, TInterests),
	Fmt="{{onto,~p}, {onto,~p}, {'$lit',~p,string}}.~n",
	Fmt1="{{onto,~p}, {onto,~p}, {'$lit',~p,int}}.~n",
	Fmt2="{{onto,~p}, {onto,~p}, {onto,~p}}.~n",
	io:format(Dev,Fmt, [Num,"name",Name]),
	io:format(Dev,Fmt, [Num,"familyName",FName]),
	io:format(Dev,Fmt, [Num,"interest",Interest]),
	io:format(Dev,Fmt1, [Num,"age",20+random:uniform(20)]),
	io:format(Dev,Fmt2, [Num,"friend",random:uniform(gb_trees:size(TFNames))-1]),
	gt_loop(TNames,TFNames,TInterests,Num-1,Dev).

cat(Filename) ->
	{ok,Dev}=file:open(Filename, [read]),
	R=io:read(Dev,no_prompt),
	cat_loop(R,Dev).

cat_loop({error,Info},_Dev) ->
	io:format("Error: ~p~n",[Info]);
cat_loop(eof,_Dev) ->
	ok;
cat_loop({ok,Term},Dev) ->
	io:format("~p~n",[Term]),
	cat_loop(io:read(Dev,no_prompt),Dev).



%%
%% Local Functions
%%

